package com.dhq.myapp.base.adapter

import androidx.recyclerview.widget.RecyclerView
import android.util.SparseArray
import android.view.View
import android.widget.TextView

/**
 * DESC RecycleView的公用ViewHolder
 * Created by admin on 2016/9/7.
 */
class RvBaseHolder(itemView: View, private val viewType: Int) : RecyclerView.ViewHolder(itemView) {

    /**
     * save view ids
     */
    private val sparseArray = SparseArray<View>()

    private val rootView: View = itemView

    /**
     * 获取跟布局
     */
    fun getRootView(): View = rootView

    /**
     * 获取布局类型
     */
    fun getViewType(): Int = viewType

    /**
     * 根据id获取控件
     */
    @Suppress("UNCHECKED_CAST")
    fun <T : View> getView(resId: Int): T {
        var view = sparseArray.get(resId)
        if (view == null) {
            view = rootView.findViewById(resId)
            sparseArray.put(resId, view)
        }
        return view as T
    }

    fun setText(id: Int, str: String): RvBaseHolder {
        val view = getView<View>(id)
        if (view is TextView) {
            view.text = str
        }
        return this
    }
}